package org.example.controller;

import org.example.bean.R;
import org.example.dto.UserUsageRecordDTO;
import org.example.entity.Contents;
import org.example.entity.Users;
import org.example.mapper.ContentsMapper;
import org.example.mapper.UsersMapper;
import org.example.service.UserUsageRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin(origins = "*")
public class UserUsageRecordController {
    
    @Autowired
    private UserUsageRecordService userUsageRecordService;
    
    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private ContentsMapper contentsMapper;
    
    /**
     * 调试接口：检查数据库中的数据
     */
    @GetMapping("/debug/contents")
    public R debugContents() {
        try {
            List<Contents> allContents = contentsMapper.selectList(null);
            return new R().setMsg("调试成功").add("totalContents", allContents.size()).add("contents", allContents);
        } catch (Exception e) {
            return new R().setCode(500).setMsg("调试失败: " + e.getMessage());
        }
    }
    
    /**
     * 调试接口：检查特定用户的内容记录
     */
    @GetMapping("/debug/user-contents")
    public R debugUserContents(@RequestParam String openid) {
        try {
            Users user = usersMapper.getUserByOpenid(openid);
            if (user == null) {
                return new R().setCode(404).setMsg("用户不存在");
            }
            
            List<Contents> userContents = contentsMapper.getContentsByUserId(user.getId());
            Integer totalPointsUsed = contentsMapper.getTotalPointsUsedByUserId(user.getId());
            
            // 检查所有contents记录
            List<Contents> allContents = contentsMapper.selectList(null);
            
            // 尝试使用字符串比较
            List<Contents> userContentsAsString = contentsMapper.getContentsByUserIdAsString(String.valueOf(user.getId()));
            
            return new R().setMsg("调试成功")
                    .add("userId", user.getId())
                    .add("userContents", userContents)
                    .add("totalPointsUsed", totalPointsUsed)
                    .add("contentCount", userContents.size())
                    .add("allContentsCount", allContents.size())
                    .add("allContents", allContents)
                    .add("userContentsAsString", userContentsAsString)
                    .add("userContentsAsStringCount", userContentsAsString.size());
        } catch (Exception e) {
            return new R().setCode(500).setMsg("调试失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据openid查询用户功能使用记录
     * @param openid 微信openid
     * @return 用户功能使用记录
     */
    @GetMapping("/user/usage-records")
    public R getUserUsageRecord(@RequestParam String openid) {
        try {
            UserUsageRecordDTO record = userUsageRecordService.getUserUsageRecordByOpenid(openid);
            if (record == null) {
                return new R().setCode(404).setMsg("用户不存在");
            }
            return new R().setMsg("查询成功").add("data", record);
        } catch (Exception e) {
            return new R().setCode(500).setMsg("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询用户功能使用记录
     * @param userId 用户ID
     * @return 用户功能使用记录
     */
    @GetMapping("/user/usage-records/{userId}")
    public R getUserUsageRecordByUserId(@PathVariable Long userId) {
        try {
            UserUsageRecordDTO record = userUsageRecordService.getUserUsageRecordByUserId(userId);
            if (record == null) {
                return new R().setCode(404).setMsg("用户不存在");
            }
            return new R().setMsg("查询成功").add("data", record);
        } catch (Exception e) {
            return new R().setCode(500).setMsg("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据openid查询用户功能使用记录（分页）
     * @param openid 微信openid
     * @param page 页码（从1开始）
     * @param size 每页大小
     * @return 用户功能使用记录
     */
    @GetMapping("/user/usage-records/page")
    public R getUserUsageRecordWithPage(
            @RequestParam String openid,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            UserUsageRecordDTO record = userUsageRecordService.getUserUsageRecordByOpenidWithPage(openid, page, size);
            if (record == null) {
                return new R().setCode(404).setMsg("用户不存在");
            }
            return new R().setMsg("查询成功").add("data", record).add("page", page).add("size", size);
        } catch (Exception e) {
            return new R().setCode(500).setMsg("查询失败: " + e.getMessage());
        }
    }
} 